package UseMap.UseTreeMap;

import java.util.Comparator;
import java.util.StringJoiner;
import java.util.TreeMap;

public class TreeMapPractice {
    public static void main(String[] args) {
        // practice01();
        // practice02();
        practice03();
    }
    // 自定义对象的生序和降序
    public static void practice01(){
        // TreeMap添加自定义对象
        // 默认升序
        TreeMap<Integer,String> tm = new TreeMap<>();
        tm.put(1,"小平");
        tm.put(3,"小绿");
        tm.put(2,"多睡");
        tm.put(5,"翘");
        tm.put(4,"小红");
        System.out.println(tm);
        // 自定义降序
        TreeMap<Integer, String> tm2 = new TreeMap<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 -o1;
            }
        });
        tm2.put(1,"小平");
        tm2.put(3,"小绿");
        tm2.put(2,"多睡");
        tm2.put(5,"翘");
        tm2.put(4,"小红");
        System.out.println(tm2);
    }

    // 存储自定义对象
    public static void practice02(){
        TreeMap<Student,String> tm = new TreeMap<>();
        Student s1 = new Student("小平",18);
        Student s2 = new Student("小绿",19);
        Student s3 = new Student("小红",20);
        tm.put(s1,"安徽");
        tm.put(s2,"上海");
        tm.put(s3,"江苏");
        System.out.println(tm);
    }


    public static void practice03(){
        String str = "abcadcbdbcabdcb";
        TreeMap<Character,Integer> tm = new TreeMap<>();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if(tm.containsKey(c)){
                Integer count = tm.get(c);
                count++;
                tm.put(c,count);
            }else {
                tm.put(c,1);
            }
        }
        // 拼接方式一: StringBuilder
        StringBuilder sb = new StringBuilder();
        tm.forEach((c,s)->{
            sb.append(c).append("(").append(s).append(")");
        });
        System.out.println(sb);
        // 拼接方式二
        StringJoiner sj = new StringJoiner("","","");
        tm.forEach((c,s)->{
            sj.add(c+"").add("(").add(s+"").add(")");
        });
        System.out.println(sj);

    }
}
